<template>
  <view class="uv-page" style="background-color: #fff;">
    <view class="uv-demo-block">
      <view class="uv-demo-block__content">
        <uv-form :model="form" :rules="rules" ref="form1" labelWidth="auto">
          <uv-form-item prop="title" required label="标题:" borderBottom>
            <uv-input v-model="form.title" border="none" placeholder="请填写标题"></uv-input>
          </uv-form-item>
          <uv-form-item prop="content" required label="内容:" borderBottom labelPosition="top">
            <uv-textarea v-model="form.content" placeholder="请输入内容"></uv-textarea>
          </uv-form-item>

          <uv-form-item prop="enclosure" label="附件:" borderBottom>
            <view style="display: flex;align-items: flex-start;">
              <uv-upload :fileList="fileList1" name="1" multiple :maxCount="10" @afterRead="afterRead"
                         :uploadText="pictureText" @delete="deletePic" :disabled="pictureDisabled"
                         width="80" :deletable="!pictureDisabled" height="80"></uv-upload>
            </view>
          </uv-form-item>
          <uv-form-item prop="isAllUser" label="用户:" borderBottom>
            <uv-radio-group v-model="form.isAllUser">
              <uv-radio :name="1" label="所有人" key="1"></uv-radio>
              <uv-radio :name="2" label="自定义" key="2"></uv-radio>
            </uv-radio-group>
          </uv-form-item>
          <uv-form-item prop="users" label="请勾选:" borderBottom v-if="form.isAllUser === 2" labelPosition="top">
            <view class="tags-container">
              <view class="tag-item" v-for="(item, index) in  checkUserBox" :key="index">
                <uv-tags :text="item.name" size="mini" :plain="!item.checked" :name="index"
                         @click="checkboxClick"></uv-tags>
              </view>
            </view>
          </uv-form-item>
        </uv-form>

        <uv-button type="primary" text="提交" customStyle="margin-top: 10px" @click="submit"></uv-button>
        <view>

        </view>
      </view>
    </view>
  </view>
</template>
<script>

import NoticeAPI from '@/api/notice'
import CommonAPI from '@/api/common'
import UploadAPI from '@/api/upload'

export default {
  data() {
    return {
      checkUserBox: [], // 待选用户列表
      form: {
        enclosure: '',
        content: '',
        title: '',
        createTime: '',
        userName: '',
        readUsers: [],
        users: [],
        isAllUser: 1
      },

      rules: {
        title: {
          required: true,
          message: '请输入标题',
          trigger: ['blur']
        },
        content: {
          required: true,
          message: '请输入通知内容',
          trigger: ['blur']
        }
      },
      fileList1: [], // 上传的附件
      pictureDisabled: false,
      pictureText: '',

    }
  },

  onReady() {
    // 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
    this.$refs.form1.setRules(this.rules)
  },
  onLoad() {
    this.getUserList()
  },
  methods: {
    getUserList() {
      CommonAPI.userList().then(res => {
        if (res.code !== 200) {
          return
        }
        this.checkUserBox =
            res.data && res.data.map((item, index) => {
              return {
                checked: false,
                ...item
              }
            })
      })
    },
    // 提交
    submit() {

      this.form.enclosure = this.fileList1.map(i => i.url).join(',')

      // 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
      this.$refs.form1.validate().then(res => {
        this.form.users = this.checkUserBox.filter(item => item.checked).map(item => {
          return {
            id: item.id,
            name: item.name
          }
        })

        NoticeAPI.noticeSubmit(this.form).then(res => {
          if (res.code === 200) {
            uni.showToast({
              icon: 'success',
              title: '提交成功'
            })
          }
          // 返回首页
          uni.reLaunch({
            url: '/pages/msg/msg'
          })
        })
      }).catch(errors => {
        uni.showToast({
          icon: 'error',
          title: '校验失败'
        })
      })
    },

    checkboxClick(name) {
      this.checkUserBox[name].checked = !this.checkUserBox[name].checked
    },

    // 删除图片
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1)
    },
    // 新增图片
    async afterRead(event) {
      console.info(event)
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file)
      let fileListLen = this[`fileList${event.name}`].length
      lists.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: 'uploading',
          message: '上传中'
        })
      })
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].url)
        let item = this[`fileList${event.name}`][fileListLen]
        this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
          status: 'success',
          message: '',
          url: result
        }))
        fileListLen++
      }
    },
    async uploadFilePromise(url) {
      let data = await UploadAPI.uploadFile(url)
      return data.link
    }
  }
}
</script>
<style lang="scss" scoped>
.uv-page {
  padding: 15px 15px 40px 15px;
}

.uv-demo-block {
  margin-bottom: 22px;
}

.uv-demo-block__title {
  font-size: 14px;
  color: #8f9ca2;
  margin-bottom: 8px;
}

.uv-demo-block__title {
  font-size: 14px;
  color: #8f9ca2;
  margin-bottom: 8px;
}

.uv-demo-block__content {
  flex-direction: row;
  flex-wrap: wrap;
  align-content: center;
}

.uv-page__tag-item {
  margin-right: 20px;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
}

.tag-item {
  margin: 1px; /* 根据需要调整间距 */
}
</style>